package com.redsoft.spirit.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.redsoft.spirit.dao.PageElementRepository;
import com.redsoft.spirit.dao.PageRepository;
import com.redsoft.spirit.entity.ComCodeTable;
import com.redsoft.spirit.entity.Page;
import com.redsoft.spirit.entity.PageElement;
import com.redsoft.spirit.util.BeanUtils;

/**
 * 
 *	页面管理service
 * <pre>
 * 	页面管理service
 * </pre>
 * 
 * @author 杨雷
 * 
 * 2017.06.16
 * 
 * @since 1.0
 *
 */
@Service
@Transactional
public class PageService {
	
	@Autowired
	private PageRepository pageRepository;
	@Autowired
	private PageElementRepository pageElementRepository;

	/**
	 * 
	 * 新增或者修改.
	 * <pre>
	 * 	新增或者修改
	 * </pre>
	 * 
	 * @author 杨雷
	 * @param codeTable
	 * @throws Exception 
	 */
	public void save(Page page) throws Exception {
		if("".equals(page.getId())) {
			pageRepository.save(page);		
		} else {
			Page pageOld = pageRepository.findById(page.getId());
			
			BeanUtils.copyBeanNotNull2Bean(page, pageOld);
			
			pageRepository.save(pageOld);
		}
	}

	/**
	 * 
	 * 删除的时候把选择的页面id和所有页面元素子项都删除掉.
	 * <pre>
	 * 	删除的时候把选择的页面id和所有子项都删除掉
	 * </pre>
	 * 
	 * @author 杨雷
	 * @param id
	 */
	public void deleteAllById(String id) {
		List <PageElement> elements = pageElementRepository.findByPageId(id);
		
		for (PageElement element : elements) {
			pageElementRepository.delete(element);
		}
		pageRepository.delete(id);
	}

	/**
	 * 
	 * 查询所选模块下的所有页面，可分页.
	 * <pre>
	 * 	查询所选模块下的所有页面，可分页
	 * </pre>
	 * 
	 * @author 杨雷
	 * @param moudleInnerName 
	 * @param offset
	 * @param limit
	 * @param searchKey
	 * @return
	 */
	public Map getJsonData(String moudleInnerName, int offset, int limit, String searchKey) {

		String sql = "select p.*, c.item_name moudleName from sys_page p, com_code_table c where p.component_inner_name = c.inner_name and p.component_inner_name = :moudle";
		
		Map map = new HashMap<>();
		map.put("moudle", moudleInnerName);
		//根据公司名称搜索
		if (searchKey != null && !"".equals(searchKey)) {
			map.put("searchKey", "%" + searchKey + "%");
			
			sql += " and p.page_name like :searchKey";
		}
		String countSql = "select count(0) from (" + sql +") a";
		
		return pageRepository.sqlQuery(sql, countSql, map, offset, limit, "count", "rows");
	}

	/**
	 * 
	 * 根据组件id查询页面.
	 * <pre>
	 * 	根据组件id查询页面
	 * </pre>
	 * 
	 * @author 杨雷
	 * @param id
	 * @return
	 */
	public List<Page> getPagesByComponentId(String id) {
		String sql = "select *from sys_page p where p.component_inner_name = (select c.inner_name from com_code_table c where c.id=?)";
		
		return pageRepository.sqlQuery(sql, id);
	}
}
